<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>d3.js</title>
    <!-- <script src="d3.v7.min.js"></script> -->
    <script src="jquery-3.6.4.js"></script>
    <script src="d3.v5.js"></script>
    <style>
        rect{
            fill:steelblue;
        }
        text{
            font-size:1.4em;
        }

    </style>
</head>
<body>

 

    <div class="canva">
        
    </div>

   

   
    
</body>
<script>
  //https://www.youtube.com/watch?v=NlBt-7PuaLk&list=PL9yYRbwpkykvOXrZumtZWbuaXWHvjD8gi&index=7

  const svgWidth=500,svgHeight=200;
  const rectWidth = 24,rectPadding = 2;
  const leftMargin = 10,topMaggin =10;
  const labelLeftMargin=20,labelTopMagin=10;
  const margin = {left:130,right:80,top:20,bottom:90}
  const innerWidth = svgWidth - margin.left - margin.right;
  const innerHeight = svgHeight - margin.top - margin.bottom;

  console.log(innerWidth,innerHeight);
   const canvas = d3.select(".canva");
   
   const svg = canvas.append("svg");
   svg.attr('width',svgWidth )
     .attr('height',svgHeight);

  const outData = null;

  const render = data=> {

    // 比例尺 domain时实际数据，range是屏幕数据，缩放到range大小
    var xScale = d3.scaleTime()
    .domain([d3.min(data,d=>Math.min(d.start,d.end)),
             d3.max(data,d=>Math.max(d.start,d.end))])
    .range([0,innerWidth])


    console.log(xScale(new Date("2023-03-01")));

    var yScale = d3.scaleBand()
    .domain(data.map(d=>d.employee+"."+d.project)) // data.map()返回一个新的数组
    .range([0,innerHeight])
    .padding(0.1); //设置间隔
    

    
    // 更易维护
    const xValue = d=>{ return xScale(d.end) - xScale(d.start)};
    const yValue = d=>d.employee+"."+d.project;

    var g = svg.append('g')
        .attr('transform',`translate(${margin.left},${margin.top})` )

    // y坐标轴
     yAxis = d3.axisLeft(yScale);
     yAxis(g.append("g")); // a.append("g").call(yAxis);//等同于
    //上两句话等价于 g.append("g").call(d3.axisLeft(yScale))

    // x坐标
    const formatTime = d3.timeFormat("%Y-%m-%d");
    g.append("g").call(d3.axisBottom(xScale).tickFormat(formatTime).ticks(d3.timeMonth.every(1)))
        .attr('transform', `translate(0,${innerHeight})`)
        .attr('class',"axis-x" )
        
    d3.select(".axis-x")
        .selectAll(".tick text")
        .attr("transform","rotate(45)")
        // .attr('transform',"translate(0,4)" )
        .style("font-size","12px")
        .style("fill","red")
        .attr("text-anchor","start")
        .style('dominant-baseline',"middle" )
       

    // RECTS
    g.selectAll("rect").data(data)
    .enter().append("rect").attr('width',function(d,i){
        
        return xValue(d);
        //return xScale(d.population)
       //return d.population;
      })
    .attr('height', function(d,i){
        // return rectWidth;
        console.log("yScale.bandwidth()"+yScale.bandwidth());
        return yScale.bandwidth();
    })
    .attr('x', function(d,i){
        return xScale(d.start)
    }) // 向右移动
    .attr('y', function(d,i){
        // 向下移动
        return yScale(yValue(d))
    } )
    .attr('fill', "orange")


    //Label start 。注意应该加个class
    var startG= g.append("g")
    var text2 = startG.selectAll("text.start-label")
    .data(data)
    .enter()
    .append("text")
    .text(function(d,i){
        return formatDate(d.start);
    })
    .attr('y',function(d,i){
      //  return labelTopMagin+ (rectWidth+rectPadding)*i ;
        return labelTopMagin+ yScale(yValue(d));
    } )
    .attr('x',function(d,i){
        return  xScale(d.start);
    } )
    .attr('stroke',"black" )
    .style('font-size',"12px")
    .style("text-anchor", "start") // 将文本水平居中对齐
    .style("dominant-baseline", "middle"); // 将文本垂直居中对齐

    // Label EndDate
    var endG = g.append("g")
    var text3 = endG.selectAll("text.end-label")
    .data(data)
    .enter()
    .append("text")
    .text(function(d,i){
        return formatDate(d.end);
    })
    .attr('y',function(d,i){
      //  return labelTopMagin+ (rectWidth+rectPadding)*i ;
        return labelTopMagin+ yScale(yValue(d));
    } )
    .attr('x',function(d,i){
        return  xScale(d.end);
    } )
    .attr('stroke',"black" )
     .style('font-size',"12px")
    .style("text-anchor", "start") // 将文本水平居中对齐
    .style("dominant-baseline", "middle"); // 将文本垂直居中对齐
    
  }//end of render()


   
  d3.csv('d3-p-002.csv').then( data=>{
    
    data.forEach(d => {
        console.log(d);
        d.start = new Date(d.start);
        d.end = new Date(d.end);
    });
    render(data);
  })

  function formatDate(today){
    // const today = new Date();
    const year = today.getFullYear().toString().substr(0,2);
    let month = (today.getMonth() + 1).toString();
    if (month.length === 1) {
    month = '0' + month;
    }
    let day = today.getDate().toString();
    if (day.length === 1) {
    day = '0' + day;
    }
    const yyyymmdd = year +"/"+ month +"/"+ day;
    return yyyymmdd;
  }

</script>

</html>